package com.scalar.chiptrack.adaptor.ikanos.ase;

import com.scalar.chiptrack.adaptor.AdaptorUtils;
import com.scalar.chiptrack.adaptor.AdaptorConstants;
import com.scalar.chiptrack.adaptor.dao.AdaptorRunInfo;
import com.scalar.chiptrack.jobs.JobHandler;
import com.scalar.chiptrack.users.VendorAdaptor;
import com.scalar.chiptrack.users.dao.AdaptorSetUpDAO;
import com.scalar.chiptrack.utils.Logger;
import com.scalar.chiptrack.utils.DateUtil;
import com.scalar.chiptrack.utils.StringUtils;
import com.scalar.ScalarException;

import HTTPClient.HTTPConnection;
import HTTPClient.HTTPResponse;
import HTTPClient.CookieModule;
import HTTPClient.NVPair;
import HTTPClient.Cookie;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Calendar;
/**
 * User: ChandraSekhar
 * Date: Jul 7, 2008
 * Time: 7:56:13 PM
 */
public class ASEAdaptor extends JobHandler implements AdaptorConstants
{

    private static String HOST = "aservice.aseglobal.com";
    private static int PORT = 80;

    //Login URI
    private static String FORM_LOGIN_ACTION     = "/Login.do;jsessionid=";
    //Assembly WIP URI's
    //private static String NONBUMP_ACTION_1      = "/ReportShowPre.do?reportId=3&FLAG_REPORT_NO_RESULT=1";
    private static String NONBUMP_ACTION_2      = "/reports/assy/ASSYWIPReport.do";

    //AssyYield report URI's
    //private static String YIELD_RPT_ACTION_1    = "/ReportShowPre.do?reportId=6&FLAG_REPORT_NO_RESULT=1";
    private static String YIELD_RPT_ACTION_2    = "/reports/assy/ASSYYieldReport.do";
    //Assy Ship report URI's
    //private static String SHIP_RPT_ACTION_1     = "/ReportShowPre.do?reportId=7&FLAG_REPORT_NO_RESULT=1";
    private static String SHIP_RPT_ACTION_2     = "/reports/assy/ASSYShipmentReport.do";
    // WAFER SORT Yield
    //private static String SORT_BIN_RPT_ACTION_1 = "/ReportShowPre.do?reportId=36&FLAG_REPORT_NO_RESULT=1";
    private static String SORT_BIN_RPT_ACTION_2 = "/reports/aset/WSYieldReport.do";
    //FINAT TEst Yiled
    //private static String TEST_BIN_RPT_ACTION_1 = "/ReportShowPre.do?reportId=13&FLAG_REPORT_NO_RESULT=1";
    private static String TEST_BIN_RPT_ACTION_2 = "/reports/aset/FTYieldReport.do";

    //DownLoad Actions
    //private static String DOWNLOAD_ACTION       = "/reports/funcs/DownloadPre.do";
    private static String DOWNLOAD_ACTION_1     = "/reports/funcs/DownloadAction.do";
    //Logout URI
    private static String FORM_LOGOUT_ACTION    = "/Logout.do";

    public static String FILE_NAME_IK_SORT_YIELD  = "IK_SORT_Yield_Report";
    public static String FILE_NAME_GW_SORT_YIELD  = "GW_SORT_Yield_Report";
    public static String FILE_NAME_IK_FT_YIELD    = "IK_FT_Yield_Report";
    public static String FILE_NAME_GW_FT_YIELD    = "GW_FT_Yield_Report";

    public static final String ADAPTOR_NAME     = "ASET_YIELD";

    private Logger m_adaptorLogger  = null;
    private String m_dataOutputDir  = null;
    private String m_username       = null;
    private String m_password       = null ;
    private String m_customerId     = null ;
    private int    m_adaptor_id     = -1;

    public ASEAdaptor() throws ScalarException
    {
        try
        {
           VendorAdaptor vendorAdaptor = AdaptorSetUpDAO.getVendorAdaptorDetailsByVendorNameAndLocation( VENDOR_NAME_ASET, LOCATION_TYPE_SORT);

            m_username = vendorAdaptor.getUserId().trim();
            m_password = vendorAdaptor.getPassWord().trim();
            m_dataOutputDir = vendorAdaptor.getOutPutDirectory().trim();
            m_customerId = vendorAdaptor.getCustomerId().trim();
            
            if ( m_dataOutputDir != null )
            {
                if ( m_dataOutputDir.endsWith( "/" ) || m_dataOutputDir.endsWith( "\\" ) )
                {
                    m_dataOutputDir = m_dataOutputDir + m_username;
                }
                else
                {
                    m_dataOutputDir = m_dataOutputDir + "/" + m_username;
                }

                AdaptorUtils.makeAllAdaptorDirs( m_dataOutputDir );
                m_adaptorLogger  =  AdaptorUtils.getAdaptorLogger( m_dataOutputDir, VENDOR_NAME_ASET );
                AdaptorUtils.setLogger( m_adaptorLogger );
            }
        }
        catch ( ScalarException se )
        {
            log( "ERROR!! ERROR!! ERROR!! Exception while loading ASE Adaptor Username, Password details from database, Exception: " + se );
            throw se;
        }
    }

    public static void main( String[] args )  throws Exception
    {

        try
        {
            new ASEAdaptor().execute();
        }
        catch ( Exception e )
        {
            e.printStackTrace();
        }
    }

    public void execute() throws Exception
    {
        m_adaptor_id = AdaptorRunInfo.saveAdaptorLastUpdatedStatus( CONSTANT_ADAPTOR, ADAPTOR_NAME, CONSTANT_SUCCESS, -1);
        //Print the header details
        AdaptorUtils.printHeader(VENDOR_NAME_ASET + "Yield", CONSTANT_ADAPTOR);

        AdaptorUtils.removeOldFiles( m_dataOutputDir, m_adaptorLogger );

        try
        {
            //login to the Site
            HTTPConnection conn = login( HOST, PORT, m_username, m_password );

            if ( conn != null )
            {
                BufferedReader reader = null;

                //Request for Turn key wip status
               /*HTTPResponse rsp = requestAssemblyWipReport( conn );
                if ( rsp != null )
                {
                    reader = new BufferedReader( new InputStreamReader( rsp.getInputStream() ) );
                    if ( reader != null )
                    {
                        System.out.println( "\tDownloading and saving the Assembly Wip Report..." );
                        log( "\tDownloading and saving the Assembly Wip Report..." );
                        AdaptorUtils.saveAsFile( reader , m_dataOutputDir, "ASSY_WIP" , FILE_EXTN_CSV);
                    }
                    else
                    {
                        log( "Could not save Assembly Wip Report from Buffer Reader" );
                        throw new ScalarException( "Could not save Assembly Wip Report from Buffer Reader" );
                    }
                }
                else
                {
                    log( "Could not create response object of Assembly Wip Report" );
                    throw new ScalarException( "Could not create response object of Assembly Wip Report" );
                }
                rsp = requestAssyYieldReport( conn );
                if ( rsp != null )
                {
                    reader = new BufferedReader( new InputStreamReader( rsp.getInputStream() ) );
                    if ( reader != null )
                    {
                        System.out.println( "\tDownloading and saving the FT yield Report..." );
                        log( "\tDownloading and saving the FT yield Report..." );
                        AdaptorUtils.saveAsFile ( reader , m_dataOutputDir, "ASSY_YIELD" ,FILE_EXTN_CSV);
                        if ( m_adaptor_id > 0 )
                        {
                            AdaptorRunInfo.saveAdaptorFileInfo( m_adaptor_id , "ASSY_YIELD", FILE_EXTN_CSV, StringUtils.formatDateandTime(DateUtil.getFormattedTimeStamp() )) ;
                        }
                    }
                    else
                    {
                        log( "Could not save FT yield Report from Buffer Reader" );
                        throw new ScalarException( "Could not save FT yield Report from Buffer Reader" );
                    }
                }
                else
                {
                    log( "Could not create response object of Test yield Report" );
                    throw new ScalarException( "Could not create response object of Test yield Report" );
                } */

                /*rsp = requestAssyShipmentReport( conn );
                if ( rsp != null )
                {
                    reader = new BufferedReader( new InputStreamReader( rsp.getInputStream() ) );
                    if ( reader != null )
                    {
                        System.out.println( "\tDownloading and saving the FT yield Report..." );
                        log( "\tDownloading and saving the FT yield Report..." );
                        AdaptorUtils.saveAsFile ( reader , m_dataOutputDir, "ASSY_SHIP" ,FILE_EXTN_CSV);
                        if ( m_adaptor_id > 0 )
                        {
                            AdaptorRunInfo.saveAdaptorFileInfo( m_adaptor_id , "ASSY_SHIP", FILE_EXTN_CSV, StringUtils.formatDateandTime(DateUtil.getFormattedTimeStamp() )) ;
                        }
                    }
                    else
                    {
                        log( "Could not save FT yield Report from Buffer Reader" );
                        throw new ScalarException( "Could not save FT yield Report from Buffer Reader" );
                    }
                }
                else
                {
                    log( "Could not create response object of Test yield Report" );
                    throw new ScalarException( "Could not create response object of Test yield Report" );
                }
                  */

                //Request for Test Yield Report
                //for (int i=0; i < m_customerId.split("#").length; i++ )
                 //IKNOS YIELD REPORT
                 HTTPResponse rsp = requestFTYieldReport( conn, m_customerId.split("#")[0] );
                 if ( rsp != null )
                 {
                    reader = new BufferedReader( new InputStreamReader( rsp.getInputStream() ) );
                    if ( reader != null )
                    {
                        System.out.println( "\tDownloading and saving the FT yield Report..." );
                        log( "\tDownloading and saving the FT yield Report..." );
                        AdaptorUtils.saveAsFile ( reader , m_dataOutputDir, FILE_NAME_IK_FT_YIELD ,FILE_EXTN_CSV);
                        if ( m_adaptor_id > 0 )
                        {
                            AdaptorRunInfo.saveAdaptorFileInfo( m_adaptor_id , FILE_NAME_IK_FT_YIELD, FILE_EXTN_CSV, StringUtils.formatDateandTime(DateUtil.getFormattedTimeStamp() )) ;
                        }
                    }
                    else
                    {
                        log( "Could not save FT yield Report from Buffer Reader" );
                        throw new ScalarException( "Could not save FT yield Report from Buffer Reader" );
                    }
                }
                else
                {
                    log( "Could not create response object of Test yield Report" );
                    throw new ScalarException( "Could not create response object of Test yield Report" );
                }
                //GLOBE SPAN  YIELD REPORT
                 rsp = requestFTYieldReport( conn, m_customerId.split("#")[1] );
                 if ( rsp != null )
                 {
                    reader = new BufferedReader( new InputStreamReader( rsp.getInputStream() ) );
                    if ( reader != null )
                    {
                        System.out.println( "\tDownloading and saving the FT yield Report..." );
                        log( "\tDownloading and saving the FT yield Report..." );
                        AdaptorUtils.saveAsFile ( reader , m_dataOutputDir, FILE_NAME_GW_FT_YIELD ,FILE_EXTN_CSV);
                        if ( m_adaptor_id > 0 )
                        {
                            AdaptorRunInfo.saveAdaptorFileInfo( m_adaptor_id , FILE_NAME_GW_FT_YIELD, FILE_EXTN_CSV, StringUtils.formatDateandTime(DateUtil.getFormattedTimeStamp() )) ;
                        }
                    }
                    else
                    {
                        log( "Could not save FT yield Report from Buffer Reader" );
                        throw new ScalarException( "Could not save FT yield Report from Buffer Reader" );
                    }
                }
                else
                {
                    log( "Could not create response object of Test yield Report" );
                    throw new ScalarException( "Could not create response object of Test yield Report" );
                }
                //Request for WasferSort Yield Report
                rsp = requestWSYieldReport( conn, m_customerId.split("#")[0] );
                if ( rsp != null )
                {
                    reader = new BufferedReader( new InputStreamReader( rsp.getInputStream() ) );
                    if ( reader != null )
                    {
                        System.out.println( "\tDownloading and saving the Sort Yield Report..." );
                        log( "\tDownloading and saving the Sort Yield Report..." );
                        AdaptorUtils.saveAsFile ( reader , m_dataOutputDir, FILE_NAME_IK_SORT_YIELD ,FILE_EXTN_CSV);
                         if ( m_adaptor_id > 0 )
                        {
                            AdaptorRunInfo.saveAdaptorFileInfo( m_adaptor_id , FILE_NAME_IK_SORT_YIELD, FILE_EXTN_CSV, StringUtils.formatDateandTime(DateUtil.getFormattedTimeStamp() )) ;
                        }
                    }
                    else
                    {
                        log( "Could not save Sort Yield Report from Buffer Reader" );
                        throw new ScalarException( "Could not save Sort Yield Report from Buffer Reader" );
                    }
                }
                else
                {
                    log( "Could not create response object of Sort Yield Report" );
                    throw new ScalarException( "Could not create response object of Sort Yield Report" );
                }

                 //Request for GLOBE SPAN WasferSort Yield Report
                rsp = requestWSYieldReport( conn, m_customerId.split("#")[1]  );
                if ( rsp != null )
                {
                    reader = new BufferedReader( new InputStreamReader( rsp.getInputStream() ) );
                    if ( reader != null )
                    {
                        System.out.println( "\tDownloading and saving the Sort Yield Report..." );
                        log( "\tDownloading and saving the Sort Yield Report..." );
                        AdaptorUtils.saveAsFile ( reader , m_dataOutputDir, FILE_NAME_GW_SORT_YIELD ,FILE_EXTN_CSV);
                         if ( m_adaptor_id > 0 )
                        {
                            AdaptorRunInfo.saveAdaptorFileInfo( m_adaptor_id , FILE_NAME_GW_SORT_YIELD, FILE_EXTN_CSV, StringUtils.formatDateandTime(DateUtil.getFormattedTimeStamp() )) ;
                        }
                    }
                    else
                    {
                        log( "Could not save Sort Yield Report from Buffer Reader" );
                        throw new ScalarException( "Could not save Sort Yield Report from Buffer Reader" );
                    }
                }
                else
                {
                    log( "Could not create response object of Sort Yield Report" );
                    throw new ScalarException( "Could not create response object of Sort Yield Report" );
                }
                //logout from the site
                logout( conn );

                if ( reader != null )
                {
                    reader.close();
                    reader = null;
                }
            }
            else
            {
                log( "Could not able to get the Connection to ASE web site" );
                throw new ScalarException( "Could not able to get the Connection to ASE web site" );
            }
        }
        catch (Exception e )
        {
            System.out.println("ERROR!! ERROR!! ERROR!! Exception while running ASE Adaptor");
            e.printStackTrace();
            throw e;
        }
    }

    private HTTPConnection login( String host, int port, String userId, String password ) throws Exception
    {
        HTTPConnection conn = null;
        String sessionId    = null;

        conn = new HTTPConnection( host, port );

        NVPair defaultHeaders[] = new NVPair[5];
        defaultHeaders[0] = new NVPair( "Accept", "image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-shockwave-flash, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*" );
        defaultHeaders[1] = new NVPair( "Accept-Language", "en-us" );
        defaultHeaders[2] = new NVPair( "User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0; SOL/4.0; .NET CLR 2.0.50727)" );
        defaultHeaders[3] = new NVPair( "Host", host );
        defaultHeaders[4] = new NVPair( "Proxy-Connection", "Keep-Alive" );

        // Accept all cookies
        CookieModule.setCookiePolicyHandler( null );
        conn.addDefaultModule( CookieModule.class, -1 );
        conn.setDefaultHeaders( defaultHeaders );
		CookieModule.discardAllCookies();
        System.out.print( "Trying to login...." );
        log( "\nTrying to log in... " );

        HTTPResponse rsp = conn.Get( "/" );

        readData( rsp, 1 );

        Cookie[] cookie = CookieModule.listAllCookies();

        for ( int i = 0; i < cookie.length; i++ )
        {
            //System.out.println("i="+i+" Name = "+cookie[i].getName()+" Value = "+cookie[i].getValue());
            if ( cookie[i].getName() != null && cookie[i].getName().trim().equalsIgnoreCase( "JSESSIONID" ) )
            {
                sessionId = cookie[i].getValue();
            }
        }

        //System.out.println("sessionId" + sessionId );

        NVPair[] formData = new NVPair[3];

        formData[0] = new NVPair( "loginID", userId );
        formData[1] = new NVPair( "password", password );
        formData[2] = new NVPair( "login", "Login" );

        rsp = conn.Post( FORM_LOGIN_ACTION +sessionId, formData );

        readData( rsp, 0 );

        System.out.println( "done." );
        log( "done" );
        return conn;
    }
   /**
    *  To Log out from the ASE K site
    * @param conn
    * @throws Exception
    */
    private void logout( HTTPConnection conn ) throws Exception
    {
        System.out.print( "Submitting Request for logout......" );

        log( "\nSubmitting Request for logout...." );

        HTTPResponse rsp = conn.Get( FORM_LOGOUT_ACTION );
        readData( rsp, 1 );

        System.out.println( "done" );
        log( "done." );
    }
     /**
      * To get the ASEK Assembly Wip(Non-Bumping) Status Assembly details sheet
      * @param conn
      * @return HTTPRespone
      * @throws Exception
      */
    private HTTPResponse requestAssemblyWipReport( HTTPConnection conn ) throws Exception
    {
        BufferedReader reader = null;
        String line = null;
        String downLoadUri = null;

        NVPair[] formData = new NVPair[9];

        formData[0] = new NVPair("custId","2I");
        formData[1] = new NVPair( "wipStatus", "" );
        formData[2] = new NVPair( "device", "" );
        formData[3] = new NVPair( "pkgType", "" );
        formData[4] = new NVPair( "leadCnt", "" );
        formData[5] = new NVPair( "custLot", "" );
        formData[6] = new NVPair( "aseSch", "" );
        formData[7] = new NVPair( "erc", "" );
        //formData[8] = new NVPair( "queryBtn", "Query" );

        System.out.println( "Submitting request for Assembly Wip Report....." );

        HTTPResponse rsp = conn.Post( NONBUMP_ACTION_2, formData );

        readData( rsp,0 );

        NVPair[] tempFormData = new NVPair[2];

        tempFormData[0] = new NVPair( "reportId", "3" );
        tempFormData[1] = new NVPair( "fileFormat", "csv" );
        
        rsp = conn.Post( DOWNLOAD_ACTION_1, tempFormData );

        System.out.print( "\tReading intermediate information II...." );

        reader = new BufferedReader( new InputStreamReader( rsp.getInputStream() ) );
                
        while ( ( line = reader.readLine() ) != null )
        {
            //System.out.println("Line:"+line);
            if (line.indexOf("GetFileAction.do") != -1 )
            {
                System.out.println("Line:"+line.split("\"")[1]);
                downLoadUri =  line.split("\"")[1];
                break;
            }
        }
        //readData(rsp, 0 );
        rsp = conn.Get( downLoadUri );

        System.out.println( "done" );
        
        return rsp;
    }
    /**
     *  To get the ASEK Assembly yield report response from site
     * @param //conn
     * @return HTTPResponse
     * @throws Exception
     */

   public HTTPResponse requestAssyYieldReport( HTTPConnection conn ) throws Exception
    {
        BufferedReader reader = null;
        String line = null;
        String downLoadUri = null;

        Calendar calendar = Calendar.getInstance();
        String toDate = StringUtils.formatDateToString( calendar.getTime(), "yyyy/MM/dd" );
        calendar.add( Calendar.DATE, -7 );
        String fromDate = StringUtils.formatDateToString( calendar.getTime(), "yyyy/MM/dd" );

        System.out.println( "TO Date " + toDate );
        System.out.println( "FROM Date " + fromDate );

        System.out.println( "Submitting request for Yield Report....." );

         NVPair[] formData = new NVPair[8];

        formData[0] = new NVPair("custId",m_customerId);
        formData[1] = new NVPair( "aseShipDateFrom", fromDate );
        formData[2] = new NVPair( "aseShipDateTo", toDate );
        formData[3] = new NVPair( "device", "" );
        formData[4] = new NVPair( "pkgType", "" );
        formData[5] = new NVPair( "leadCnt", "" );
        formData[6] = new NVPair( "custLot", "" );
        //formData[7] = new NVPair( "queryBtn", "Query" );

        HTTPResponse rsp = conn.Post( YIELD_RPT_ACTION_2, formData );
        readData( rsp, 0 );

        NVPair[] tempFormData = new NVPair[2];

        tempFormData[0] = new NVPair( "reportId", "6" );
        tempFormData[1] = new NVPair( "fileFormat", "csv" );

        rsp = conn.Post( DOWNLOAD_ACTION_1, tempFormData );
        System.out.print( "\tReading intermediate information II...." );
        reader = new BufferedReader( new InputStreamReader( rsp.getInputStream() ) );

        while ( ( line = reader.readLine() ) != null )
        {
            //System.out.println("Line:"+line);
            if (line.indexOf("GetFileAction.do") != -1 )
            {
                //System.out.println("ASSYYIELD ACTION Line:"+line.split("\"")[1]);
                downLoadUri =  line.split("\"")[1];
                break;
            }
        }
        //readData(rsp, 0 );
        rsp = conn.Get( downLoadUri );

        //readData(rsp, 1);
        System.out.println( "done" );

        return rsp;
    }

    private HTTPResponse requestWSYieldReport( HTTPConnection conn, String customerId ) throws Exception
    {
        BufferedReader reader = null;
        String line = null;
        String downLoadUri = null;

        NVPair[] formData = new NVPair[9];

        formData[0] = new NVPair( "custId",customerId );
        formData[1] = new NVPair( "closeDateFrom", DateUtil.getPreviousDate(7, "yyyy/MM/dd") );
        formData[2] = new NVPair( "closeDateTo", DateUtil.getCurrentDate("yyyy/MM/dd") );
        formData[3] = new NVPair( "device", "" );
        formData[4] = new NVPair( "custLot", "" );
        formData[5] = new NVPair( "schedule", "" );
        
        //formData[8] = new NVPair( "queryBtn", "Query" );

        System.out.println( "Submitting request for Wafer Sort Yield Report....." );

        HTTPResponse  rsp = conn.Post( SORT_BIN_RPT_ACTION_2, formData );

        readData( rsp,0 );

        NVPair[] tempFormData = new NVPair[2];

        tempFormData[0] = new NVPair( "reportId", "36" );
        tempFormData[1] = new NVPair( "fileFormat", "csv" );

        rsp = conn.Post( DOWNLOAD_ACTION_1, tempFormData );

        System.out.println( "\tReading intermediate information II...." );

        reader = new BufferedReader( new InputStreamReader( rsp.getInputStream() ) );

        while ( ( line = reader.readLine() ) != null )
        {
            //System.out.println("Line:"+line);
            if (line.indexOf("GetFileAction.do") != -1 )
            {
                //System.out.println("\tWS Yield Line:"+line.split("\"")[1]);
                downLoadUri =  line.split("\"")[1];
                break;
            }
        }
        //readData(rsp, 0 );
        //System.out.println("downLoadUri = " + downLoadUri);
        rsp = conn.Get( downLoadUri );


        return rsp;
    }

    private HTTPResponse requestFTYieldReport( HTTPConnection conn, String customerId ) throws Exception
    {
        BufferedReader reader = null;
        String line = null;
        String downLoadUri = null;

        NVPair[] formData = new NVPair[9];

        formData[0] = new NVPair( "custId",customerId );
        formData[1] = new NVPair( "closeDateFrom", DateUtil.getPreviousDate(7, "yyyy/MM/dd") );
        formData[2] = new NVPair( "closeDateTo", DateUtil.getCurrentDate("yyyy/MM/dd") );
        formData[3] = new NVPair( "device", "" );
        formData[4] = new NVPair( "pkgType", "" );
        formData[5] = new NVPair( "leadCnt", "" );
        formData[6] = new NVPair( "custLot", "" );
        formData[7] = new NVPair( "erc", "" );
        //formData[8] = new NVPair( "queryBtn", "Query" );

        System.out.println( "Submitting request for FT Yield Report....." );

        HTTPResponse  rsp = conn.Post( TEST_BIN_RPT_ACTION_2, formData );
        readData( rsp,0 );


        NVPair[] tempFormData = new NVPair[2];

        tempFormData[0] = new NVPair( "reportId", "13" );
        tempFormData[1] = new NVPair( "fileFormat", "csv" );

        rsp = conn.Post( DOWNLOAD_ACTION_1, tempFormData );

        System.out.println( "\tReading intermediate information II...." );

        reader = new BufferedReader( new InputStreamReader( rsp.getInputStream() ) );

        while ( ( line = reader.readLine() ) != null )
        {
            //System.out.println("Line:"+line);
            if (line.indexOf("GetFileAction.do") != -1 )
            {
                //System.out.println("\t FT YIELD Line:"+line.split("\"")[1]);
                downLoadUri =  line.split("\"")[1];
                break;
            }
        }
        //readData(rsp, 0 );
        //System.out.println("downLoadUri = " + downLoadUri);
        rsp = conn.Get( downLoadUri );


        return rsp;
    }
    public HTTPResponse requestAssyShipmentReport( HTTPConnection conn ) throws Exception
    {
        BufferedReader reader = null;
        String line = null;
        String downLoadUri = null;

        Calendar calendar = Calendar.getInstance();
        String toDate = StringUtils.formatDateToString( calendar.getTime(), "yyyy/MM/dd" );
        calendar.add( Calendar.DATE, -7 );
        String fromDate = StringUtils.formatDateToString( calendar.getTime(), "yyyy/MM/dd" );

        System.out.println( "TO Date " + toDate );
        System.out.println( "FROM Date " + fromDate );

        System.out.println( "Submitting request for Shipment Report....." );

         NVPair[] formData = new NVPair[12];

        formData[0] = new NVPair("custId","2I");
        formData[1] = new NVPair( "shipDateFrom", fromDate );
        formData[2] = new NVPair( "shipDateTo", toDate );
        formData[3] = new NVPair( "device", "" );
        formData[4] = new NVPair( "deviceName", "" );
        formData[5] = new NVPair( "pkgType", "" );
        formData[6] = new NVPair( "leadCnt", "" );
        formData[7] = new NVPair( "custLot", "" );
        formData[8] = new NVPair( "dnNo", "" );
        formData[9] = new NVPair( "aseSch", "" );
        formData[10] = new NVPair( "dateCode", "" );
        formData[11] = new NVPair( "erc", "" );
        //formData[11] = new NVPair( "queryBtn", "Query" );
              
        HTTPResponse rsp = conn.Post( SHIP_RPT_ACTION_2, formData );
        readData( rsp, 0 );

        NVPair[] tempFormData = new NVPair[2];

        tempFormData[0] = new NVPair( "reportId", "7" );
        tempFormData[1] = new NVPair( "fileFormat", "csv" );

        rsp = conn.Post( DOWNLOAD_ACTION_1, tempFormData );
        System.out.print( "\tReading intermediate information II...." );
        reader = new BufferedReader( new InputStreamReader( rsp.getInputStream() ) );

        while ( ( line = reader.readLine() ) != null )
        {
            //System.out.println("Line:"+line);
            if (line.indexOf("GetFileAction.do") != -1 )
            {
                //System.out.println("SHIPMENT ACTION Line:"+line.split("\"")[1]);
                downLoadUri =  line.split("\"")[1];
                break;
            }
        }
        //readData(rsp, 0 );
        rsp = conn.Get( downLoadUri );
        //readData(rsp, 0);

        return rsp;
    }

    public void readData( HTTPResponse rsp, int debug ) throws Exception
    {
        byte[] data = new byte[1024];
        
        while ( rsp.getInputStream().read( data ) != -1 )
        {
            //System.out.println("WHILING DATA....");
            if ( debug == 0 )
            {
                //System.out.println( new String( data ) );
                //log( new String( data ) );
            }

        }
    }

    private void log( String message )
    {

        if ( message == null ) return;

        if ( m_adaptorLogger != null )
        {
            synchronized ( m_adaptorLogger )
            {
                m_adaptorLogger.logDebug( message + LINE_SEPARATOR );
            }
        }
        else
        {
            System.out.println( message );
        }
    }
}

